package com.huasan.www.demon.rest.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.server.mvc.Viewable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Provider
public class RestResponseFilter implements ContainerResponseFilter{

	private static final Logger logger = LoggerFactory.getLogger(RestResponseFilter.class);
	
	private static final String[] callBackNames = {"jsonpCallback","callback"};
	
	@Override
	public void filter(ContainerRequestContext res,
			ContainerResponseContext req) throws IOException {
		String reqType = res.getHeaderString("Accept");
		if (reqType!=null && reqType.indexOf("javascript")!=-1)
			if (req.getEntity()==null || req.getStatus()!=200){
				Map map = new HashMap();
				map.put("code", req.getStatus());
				map.put("msg", req.getStatusInfo());
				req.setEntity( (new Viewable("/WEB-INF/global/error", map)) );
				return;
			}
		
		UriInfo uriInfo = res.getUriInfo();
		MultivaluedMap<String, String> queryMap = uriInfo.getQueryParameters();
		for (int i=0; i<callBackNames.length; i++){
			if ( queryMap.containsKey(callBackNames[i]) && 
					req.getEntityType() == String.class	){
				String callbackFun = queryMap.getFirst(callBackNames[i]); 
				String callback = callbackFun + "(" + req.getEntity() + ")"; 
				req.setEntity(callback);
				break;
			}
		}
	}
}
